package controllers

import (
	"github.com/astaxie/beego"
	"log"
	"os"
	"strings"
)

type JsonResult struct {
	Success bool
	Msg     string
	Count   int
	Data    interface{}
}

type FileResult struct {
	Error   int
	Message string
	Url     string
}

type BaseController struct {
	beego.Controller
	moduleName     string
	controllerName string
	actionName     string
	options        map[string]string
}

func (this *BaseController) Prepare() {
	//UserInfo = &make(models.UserInfo)
	controllerName, actionName := this.GetControllerAndAction()
	//this.moduleName = "blog"
	this.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
	this.actionName = strings.ToLower(actionName)
	log.Println("this.controllerName", this.controllerName)
	log.Println("this.actionName", this.actionName)

}

//显示模版
func (this *BaseController) View(tpl string) {
	var theme string
	theme = this.controllerName
	if theme == "" {
		theme = "home"
	}
	if _, err := os.Stat(beego.ViewsPath + "/layout1.html"); err == nil {
		this.Layout = "layout.html"
	}
	this.TplNames = theme + "/" + tpl + ".html"
}

//显示错误页
func (this *BaseController) ViewError() {
	this.Data["controllerName"] = this.controllerName
	this.Data["actionName"] = this.actionName
	if _, err := os.Stat(beego.ViewsPath + "/layout1.html"); err == nil {
		this.Layout = "layout1.html"
	}
	this.TplNames = "error.html"
}

func (this *BaseController) GetOption(name string) string {
	if v, ok := this.options[name]; ok {
		return v
	} else {
		return ""
	}
}

//json格式化输出
func (this *BaseController) ToJson(obj interface{}, msg ...string) {
	var res *JsonResult
	var m string
	if msg != nil {
		m = msg[0]
	}
	if obj == nil {
		res = &JsonResult{Success: false, Msg: m}
	} else {
		res = &JsonResult{Success: true, Data: obj, Msg: m}
	}
	this.Data["json"] = res
	this.ServeJson()
}

//json格式化输出
func (this *BaseController) ToPagerJson(obj interface{}, count int) {
	var res *JsonResult
	if obj == nil {
		res = &JsonResult{Success: false, Count: count}
	} else {
		res = &JsonResult{Success: true, Data: obj, Count: count}
	}
	this.Data["json"] = res
	this.ServeJson()
}

//json格式化输出
func (this *BaseController) ToUpLoadJson(url, msg string, err int) {
	var res *FileResult
	res = &FileResult{Error: err, Url: url, Message: msg}
	this.Data["json"] = res
	this.ServeJson()
}

//无法使用
func (this *BaseController) Get() {
	log.Println("其他路由!!")
	url := this.Ctx.Request.URL.String()
	index := strings.LastIndex(url, "/")
	isstatic := strings.LastIndex(url, ".")
	if index == 0 && isstatic == 0 {
		this.TplNames = "home" + url + ".html"
	} else if isstatic == 0 {
		this.TplNames = strings.TrimLeft(url, "/") + ".html"
	}
	log.Println(this.TplNames)
}
